/**第一题 */
type Interest = "运动" | "音乐" | "阅读";

function registerUser(
  name: string,
  age: number,
  email?: string,
  interests: Interest[] = []
): {
  name: string;
  age: number;
  email?: string;
  interests: Interest[];
} {
  if (age < 18) {
    throw new Error("年龄不能小于18岁");
  }

  return {
    name,
    age,
    email,
    interests,
  };
}
const user1 = registerUser("张三", 25, "zhang@example.com", ["运动"]);
console.log(user1); 
const user2 = registerUser("李四", 16); // 应报错：年龄太小  

// /**第二题 */
// type Product={
//     id:number,
//     name:string,
//     price:number,
// }

// type CartItem={
//     product:Product,
//     quantity:number
// }

// let cartItems : CartItem[]=[];
// function addToCart(cart: CartItem[], product: Product, quantity: number): CartItem[] {
//   let aa:CartItem={product, quantity}
//   if(aa.quantity<0){
//     throw new Error("数量不能小于0");
//   }
//   cartItems.push(aa);
//   return cartItems;
// }
// function calculateTotal(cart: CartItem[]): number {
//   let total:number = 0;
//   for (let i = 0; i < cart.length; i++) {
//       total+=cart[i].product.price*cart[i].quantity;
//   }
//   return total;
// }

// const products: Product[] = [
//   {id: 1, name: "手机", price: 2999},
//   {id: 2, name: "耳机", price: 399}
// ];

// let cart: CartItem[] = [];
// cart = addToCart(cart, products[0], 2);
// cart = addToCart(cart, products[1], 1);
// console.log(calculateTotal(cart));

// /**第三题 */
// function handleResponse<T>(response: { data: T } | { error: string }): void{
//   if ("data" in response) {
//     console.log(response.data);
//   } else {
//     throw new Error(response.error);
//   }
// }

// const successRes = { data: { id: 1, name: "测试产品" } };
// handleResponse(successRes); // 应返回 { id: 1, name: "测试产品" }

// const errorRes = { error: "未找到资源" };
// handleResponse(errorRes); // 应抛出错误 "未找到资源"

// /**第四题 */
/* interface Shape {
  type: "circle" | "rectangle";
  calculateArea(): number;
}

class Circle implements Shape {
  type: "circle" = "circle";
  constructor(public radius: number) {
    if (radius <= 0) {
      throw new Error("半径必须为正数");
    }
  }

  calculateArea(): number {
    return Math.PI * this.radius ** 2;
  }
}
class Rectangle implements Shape {
  type: "rectangle" = "rectangle";
  constructor(public width: number, public height: number) {
    if (width <= 0 || height <= 0) {
      throw new Error("宽度和高度必须为正数");
    }
  }

  calculateArea(): number {
    return this.width * this.height;
  }
}
function createShape(type: "circle" | "rectangle", ...args: number[]): Shape {
  switch (type) {
    case "circle":
      if (args.length !== 1) {
        throw new Error("创建圆形需要提供一个参数：半径");
      }
      return new Circle(args[0]);
    case "rectangle":
      if (args.length !== 2) {
        throw new Error("创建矩形需要提供两个参数：宽度和高度");
      }
      return new Rectangle(args[0], args[1]);
  }
}

const circle = createShape("circle", 5);
console.log(circle.calculateArea()); // 约78.54

const rect = createShape("rectangle", 4, 6);
console.log(rect.calculateArea()); // 24    

// /**第五题 */
// type SerializablePrimitive = string | number | boolean | null;
// type SerializableObject = { [key: string]: Serializable } & { toJSON?: never };
// type SerializableArray = Array<Serializable>;

// type Serializable = 
//   | SerializablePrimitive
//   | SerializableObject
//   | SerializableArray;

// class TypedLocalStorage<T extends Serializable> {
//   private getStorageKey(key: string): string {
//     return `typed:${key}`;
//   }

//   private getExpiryKey(key: string): string {
//     return `expiry:${key}`;
//   }

//   setItem(key: string, value: T, expires?: Date): void {
//     try {
//       const storageKey = this.getStorageKey(key);
//       localStorage.setItem(storageKey, JSON.stringify(value));
      
//       if (expires) {
//         const expiryKey = this.getExpiryKey(key);
//         localStorage.setItem(expiryKey, expires.toISOString());
//       } else {
//         localStorage.removeItem(this.getExpiryKey(key));
//       }
//     } catch (error) {
//       console.error("Failed to store value:", error);
//       throw new Error("Value is not serializable");
//     }
//   }

//   getItem(key: string): T | null {
//     const storageKey = this.getStorageKey(key);
//     const expiryKey = this.getExpiryKey(key);
    
//     const expiryString = localStorage.getItem(expiryKey);
//     if (expiryString) {
//       const expiryDate = new Date(expiryString);
//       if (expiryDate < new Date()) {
//         localStorage.removeItem(storageKey);
//         localStorage.removeItem(expiryKey);
//         return null;
//       }
//     }
    
//     const item = localStorage.getItem(storageKey);
//     if (item === null) return null;
    
//     try {
//       return JSON.parse(item) as T;
//     } catch (error) {
//       console.error("Failed to parse stored value:", error);
//       return null;
//     }
//   }
// }
// const userStorage = new TypedLocalStorage<{name: string, age: number}>();

// // 存储
// userStorage.setItem("user", {name: "张三", age: 25});

// // 读取
// const user = userStorage.getItem("user"); // 类型为 {name: string, age: number} | null

// // // 错误示例
// // userStorage.setItem("data", new Date()); // 应报错：Date不可序列化
